package com.yzf;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.yao.component.circle.R;
import com.yao.sdk.cache.filestore.FileStoreProxy;
import com.yao.sdk.util.Utils;

import java.util.ArrayList;
import java.util.List;

public class ArroundAddressListActivity extends Activity implements PoiSearch.OnPoiSearchListener, AMapLocationListener, PullToRefreshBase.OnRefreshListener2<ListView> {
    //-------------------- ↑ LocationNetworkActivity  ↑  -----------------------------
    ArrayList<String> addressInfoList = new ArrayList<String>();//搜索的地址列表
    StringBuffer sb = new StringBuffer();//拼接完整的地址
//    private LocationManagerProxy aMapLocManager = null;
    private AMapLocation aMapLocation;// 用于判断定位超时
    private Handler handler = new Handler();
    //    private LatLonPoint lp = new LatLonPoint(24.489624, 118.186387);// 默认西单广场
    private LatLonPoint lp;//
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据
    private int currentPage = 0;// 当前页面，从0开始计数
    private MyAdapter myAdapter;
    private boolean saveListBoolean;//下一页或者上拉刷新累加list
    private boolean searchBoolean;//清除不显示位置和所在城市
    private boolean show12ItemAddreassBoolean;//显示12行地址，用于搜索显示12行地址，默认排序是不显示12行地址
    private Double geoLat;
    private Double geoLng;
    private String cityName = "";
    private String selectedName = "";
    private PullToRefreshListView mListView;
    private EditText searchEt;
    private String searchWord = "";
    private String cityName1;
    private ImageView deleteImg;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption locationOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arround_address_list);
        selectedName = getIntent().getStringExtra("selectedName");
        Location();
    }

    private void Location() {
        locationClient = new AMapLocationClient(getApplicationContext());
        locationOption = new AMapLocationClientOption();
        //设置为单次定位
        locationOption.setOnceLocation(true);
        // 设置定位模式为低功耗模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        // 设置定位监听
        locationClient.setLocationListener(this);
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
        mHandler.sendEmptyMessage(Util.MSG_LOCATION_START);
    }

    Handler mHandler = new Handler(){
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                case Util.MSG_LOCATION_START:
                    break;
                //定位完成
                case Util.MSG_LOCATION_FINISH:
                    AMapLocation loc = (AMapLocation)msg.obj;
                    cityName = loc.getCity();
                    //定位成功后搜索周边商家
                    geoLat = loc.getLatitude();
                    geoLng = loc.getLongitude();
                    lp = new LatLonPoint(geoLat, geoLng);
                    search();
                    break;
                default:
                    break;
            }
        };
    };

    // 定位监听
    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Util.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    private void initView() {
        findViewById(R.id.back2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArroundAddressListActivity.this.finish();
            }
        });
        mListView = (PullToRefreshListView) findViewById(R.id.listview);
        myAdapter = new MyAdapter();
//        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        // 设置PullRefreshListView上提加载时的加载提示
        mListView.getLoadingLayoutProxy(false, true).setPullLabel("正在搜索附近的位置");
        mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在搜索附近的位置");
        mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("正在搜索附近的位置");

        // 设置PullRefreshListView下拉加载时的加载提示
        mListView.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        mListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
        mListView.getLoadingLayoutProxy(true, false).setReleaseLabel("松开加载更多...");
        mListView.setAdapter(myAdapter);
        mListView.setOnRefreshListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s = addressInfoList.get(position - 1);
                String[] split = s.split(",");
                String s1 = split[0];//截取商家名
                Intent intent = new Intent();
                intent.putExtra("shopName", s1);
                intent.putExtra("cityName", cityName1);
                setResult(RESULT_OK, intent);
                ArroundAddressListActivity.this.finish();
            }
        });
        deleteImg = (ImageView)findViewById(R.id.location_delete_img);
        deleteImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });
        searchEt = (EditText) findViewById(R.id.search_arround_et);
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //这个判断是搜索的时候不加载1，2行不显示位置和所在城市
                if (searchEt.getText().toString().equals("")) {
                    deleteImg.setVisibility(View.INVISIBLE);
                    currentPage = 0;
                    String s1 = searchEt.getText().toString();
                    searchWord = s1;
                    saveListBoolean = false;
                    searchBoolean = false;
                    show12ItemAddreassBoolean = false;
                    search();
                } else {
                    deleteImg.setVisibility(View.VISIBLE);
                    currentPage = 0;
                    String s1 = searchEt.getText().toString();
                    searchWord = s1;
                    saveListBoolean = true;
                    searchBoolean = true;
                    show12ItemAddreassBoolean = true;
                    search();
                }

            }
        });
    }

    private void search() {
        query = new PoiSearch.Query(searchWord, "", cityName);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，如：酒店，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
//        //默认全部搜索，排除优惠和团购限制
//        query.setLimitDiscount(false);
//        query.setLimitGroupbuy(false);
        query.setCityLimit(false);
        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 2000, true));//
            // 设置搜索区域为以lp点为圆心，其周围2000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        // 调用刷新完成
        if (mListView != null) {
            mListView.onRefreshComplete();
        }
        if (rCode == 0) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        //如果是下一页或者上拉刷新不要清空list
                        if (!saveListBoolean) {
                            addressInfoList.clear();
                            addressInfoList.add("不显示位置, ");
                            addressInfoList.add(poiItems.get(0).getCityName() + ", ");
                        }
                        if (searchBoolean) {
                            addressInfoList.clear();
                            searchBoolean = false;
                        }
                        for (int i = 0; i < poiItems.size(); i++) {
                            PoiItem poiItem = poiItems.get(i);
                            sb.delete(0, sb.length());
                            //得到地址的店名
                            String shopName = poiItem.getTitle();
                            sb.append(shopName + ",");
                            //得到详细地址
                            String provinceName = poiItem.getProvinceName();//省份名字
                            sb.append(provinceName);
                            //城市名字
                            cityName1 = poiItem.getCityName();
                            sb.append(cityName1);
                            String adName = poiItem.getAdName();//区
                            sb.append(adName);
                            String snippet = poiItem.getSnippet();//街号
                            sb.append(snippet + "\n");
                            addressInfoList.add(sb.toString());
                        }
                        Log.e("addressList", addressInfoList.toString());
                        if (myAdapter != null) {
                            myAdapter.notifyDataSetChanged();
                        } else {
                            initView();
                        }
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        ToastUtil.show(ArroundAddressListActivity.this,
                                R.string.no_result);
                        if (mListView != null) {
                            mListView.onRefreshComplete();
                        }

                    }
                }
            } else {
                ToastUtil
                        .show(ArroundAddressListActivity.this, R.string.no_result);

                if (mListView != null) {
                    mListView.onRefreshComplete();
                }


            }
        } else if (rCode == 27) {
            ToastUtil
                    .show(ArroundAddressListActivity.this, R.string.error_network);
        } else if (rCode == 32) {
            ToastUtil.show(ArroundAddressListActivity.this, R.string.error_key);
        } else {
            ToastUtil.show(ArroundAddressListActivity.this, getString(R.string.error_other) + rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 点击下一页poi搜索
     */
    public void nextSearch() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                saveListBoolean = true;
                poiSearch.searchPOIAsyn();
            } else {
                mListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mListView.onRefreshComplete();
                        ToastUtil.show(ArroundAddressListActivity.this, "抱歉，当前界面没有额外的数据。");
                    }
                }, 1000);
            }
        }
    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }
        ToastUtil.show(ArroundAddressListActivity.this, infomation);

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        Log.e("onPullDownToRefresh", "onPullDownToRefresh");
        nextSearch();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        Log.e("onPullUpToRefresh", "onPullUpToRefresh");
        nextSearch();
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return addressInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = getLayoutInflater().inflate(R.layout.address_item, null);
            String s = addressInfoList.get(position);

            String[] split = s.split(",");//split[0]代表商家，split[1]代表详细地址
            TextView titleName = (TextView) inflate.findViewById(R.id.titleName);
            titleName.setText(split[0]);
            TextView addressName = (TextView) inflate.findViewById(R.id.addressName);
            addressName.setText(split[1]);
            ImageView checkImg = (ImageView) inflate.findViewById(R.id.check_img);
            //用来布局第一行不显示位置，和第二行所在城市
            if (position == 1 || position == 0) {
                if (!show12ItemAddreassBoolean) {
                    if(position == 0){
                        titleName.setTextColor(getResources().getColor(R.color.blue));
                    }
                    addressName.setVisibility(View.GONE);
                    addressName.setHeight(30);
                }

            } else {
                addressName.setVisibility(View.VISIBLE);
            }
            if (selectedName.equals(split[0])) {
                checkImg.setVisibility(View.VISIBLE);
            } else {
                checkImg.setVisibility(View.GONE);
            }
            //用来设置刚刚进去默认选择不显示位置那行
            if (selectedName.equals("所在位置")) {
                if (position == 0) {
                    checkImg.setVisibility(View.VISIBLE);
                }
            }
            return inflate;
        }
    }

}
